package com.lijin.batchsys.framework.dao;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.springframework.jdbc.core.PreparedStatementSetter;
import org.springframework.jdbc.core.RowCallbackHandler;

import com.lijin.batchsys.framework.common.BatchUtil;
import com.lijin.batchsys.framework.dao.model.JobInfo;

/**
 * Description: 任务信息DAO
 *
 * (C) Copyright of China UnionPay Co., Ltd. 2010.
 */
public class JobInfoDAO extends BaseDAO {
	
	/**
	 * 获取所有的任务信息
	 * @return
	 */
	public List<JobInfo> getAllJobInfo() {
		final List<JobInfo> jobList = new ArrayList<JobInfo>();
		
		this.getJdbcTemplate().query(BatchSysSQL.getInstance().fetchSQL(BatchSysSQL.SQL_SELECT_ALL_JOB), 
				new RowCallbackHandler() {
					@Override
					public void processRow(ResultSet rs) throws SQLException {
						JobInfo jobInfo = new JobInfo();
						jobInfo.setId(rs.getInt("ID"));
						jobInfo.setJobNo(rs.getInt("JOB_NO"));
						jobInfo.setBatchNo(rs.getInt("BATCH_NO"));
						jobInfo.setJobDesc(rs.getString("JOB_DESC"));
						jobInfo.setJobCtrlFlgs(rs.getString("JOB_CTRL_FLGS"));
						jobInfo.setRecSt(rs.getString("REC_ST"));
						jobList.add(jobInfo);
					}
		});
		
		return jobList;
	}

	@SuppressWarnings("unchecked")
	public <T> List<T> listPageInfo(String sql, final int firstResult, final int endResult) {
		final List<JobInfo> jobList = new ArrayList<JobInfo>();
		
		this.getJdbcTemplate().query(sql, 
	    new PreparedStatementSetter() {
				  @Override
			      public void setValues(PreparedStatement ps) throws SQLException {
					ps.setLong(1, firstResult);
					ps.setLong(2, endResult);
				  }
		},			
		new RowCallbackHandler() {
			@Override
			public void processRow(ResultSet rs) throws SQLException {
				JobInfo jobInfo = new JobInfo();
				jobInfo.setId(rs.getInt("ID"));
				jobInfo.setJobNo(rs.getInt("JOB_NO"));
				jobInfo.setBatchNo(rs.getInt("BATCH_NO"));
				jobInfo.setJobDesc(rs.getString("JOB_DESC"));
				jobInfo.setJobCtrlFlgs(rs.getString("JOB_CTRL_FLGS"));
				jobInfo.setRecSt(rs.getString("REC_ST"));
				String chCtrlFlgs = BatchUtil.jobCtrlFlgsToChStr(jobInfo);
				jobInfo.setChJobCtrlFlgs(chCtrlFlgs);
				jobList.add(jobInfo);
			}
		});
		
		return (List<T>) jobList;
	}
	
	public int getCount(String countSql) {
		int count = this.getJdbcTemplate().queryForInt(countSql);
		return count;
	}
}
